package com.sgb.kjwl.view.ui.fragment.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppFragmentFindGoodsByMapBinding;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.home.MapSourceEntity;
import com.sgb.kjwl.model.entity.home.MapSourceSearchEntity;
import com.sgb.kjwl.model.entity.map.CargoMapEntity;
import com.sgb.kjwl.model.entity.self.TypeChooseEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceFilterEntity;
import com.sgb.kjwl.model.entity.transport.OperateGoodsSourcePlaceVO;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.link.utils.LogisticsLogUtils;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.home.FindByMapActivity;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.InquireByLetterActvity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.AddDriverInfoActivity;
import com.sgb.kjwl.view.widget.GoodsFilterPopWindow;
import com.sgb.kjwl.view.widget.transport.ChooseTypePopWindow;
import com.sgb.kjwl.viewmodel.transport.MapFindingSourceModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.router.PathLogistics;
import com.sgb.link.utils.AddressHelper;
import com.sgb.link.view.fragment.AppLazyFragment;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.DateUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Describe:
 * Author:  yangLei
 * Date:    2021/11/23
 */
public class MapFindGoodsSourceFragment extends AppLazyFragment implements AMap.OnCameraChangeListener {
    //装货地址信息
    private AMapAddressEntity loadingEntity;
    //卸货地址信息
    private AMapAddressEntity unloadingEntity;
    //选中的货物类型集合
    private ArrayList<TypeChooseEntity> goodsTypes;
    //选中的货物重量位置
    private int selectWeightPosition;//weightBeans 数据需要与传过来的地方保持一致
    private int selectRadiusPosition;// 数据需要与传过来的地方保持一致
    private Context mContext;
    private MapFindingSourceModel mViewModel;
    private AppFragmentFindGoodsByMapBinding mBinding;

    private TextureMapView mapView;
    private AMap aMap;
    private String searchCity = "";
    private String goodsTypeNos = "";//选中的货源No
    private String timeStr = "";//选中的时间
    private MapSourceEntity currSourceInfo;
    private LatLng locationLatLng;
    private CargoPublishEntity.LocationEntity loadAddress;
    private CargoPublishEntity.LocationEntity unloadAddress;
    private MapSourceSearchEntity searchEntity;
    private CargoMapEntity newestEntity;//最新的承运信息

    private BottomSheetBehavior sheetBehavior;//底部抽屉Behavior
    private GoodsFilterPopWindow carTypePop;
    private ChooseTypePopWindow goodsTypePop;//货物类型选择选择框
    private OptionsPickerView<GoodsInfoTypeEntity3> timePicker;//时间选择器
    private final List<GoodsInfoTypeEntity3> timeBeans = new ArrayList<>();
    private OptionsPickerView<TypeChooseEntity> weightPicker;//重量选择器
    private final List<TypeChooseEntity> weightBeans = new ArrayList<>();
    public List<TypeChooseEntity> goodsTypeEntities = new ArrayList<>();
    private int timePos = 0;//时间选择的位置

    private OptionsPickerView<TypeChooseEntity> radiusPicker;//重量选择器
    private final List<TypeChooseEntity> radiusBeans = new ArrayList<>();

    private boolean mIsMarkerClick;//用于标记是否是点击marker
    private boolean isPeopleMade = false;//用于标记是否是人为滑动地图
    private boolean isFirst = true;//是否是初次进入页面的视图移动
    private boolean isTakeOrders = false;//是否是接单(竞价货源，可接单和报价)

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption;
    //声明定位回调监听器
    private AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {//可在其中解析aMapLocation获取相应内容
                    if (aMapLocation.getLatitude() > 0 && aMapLocation.getLongitude() > 0) {
                        searchEntity.setSearchLatitude(aMapLocation.getLatitude());
                        searchEntity.setSearchLongitude(aMapLocation.getLongitude());
                        mViewModel.findSourceByMap(getActivity(), searchEntity);
                    }
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    MToast.showToast(getActivity(), "定位失败");
                }
            }
        }
    };

    private MapFindGoodsSourceFragment() {
    }

    public static MapFindGoodsSourceFragment newInstance(AMapAddressEntity loadingEntity, AMapAddressEntity unloadingEntity, ArrayList<TypeChooseEntity> goodsTypes, Integer selectWeightPosition, int selectRadiusPosition) {
        MapFindGoodsSourceFragment fragment = new MapFindGoodsSourceFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("loading", loadingEntity);
        bundle.putParcelable("unloading", unloadingEntity);
        bundle.putParcelableArrayList("goodsTypes", goodsTypes);
        bundle.putInt("selectWeightPosition", selectWeightPosition);
        bundle.putInt("selectRadiusPosition", selectRadiusPosition);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            loadingEntity = getArguments().getParcelable("loading");
            unloadingEntity = getArguments().getParcelable("unloading");
            selectWeightPosition = getArguments().getInt("selectWeightPosition");
            goodsTypes = getArguments().getParcelableArrayList("goodsTypes");
            selectRadiusPosition = getArguments().getInt("selectRadiusPosition");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getContext();
        mBinding = DataBindingUtil.inflate(inflater, R.layout.app_fragment_find_goods_by_map, container, false);
        mBinding.mapView.onCreate(savedInstanceState);
        sheetBehavior = BottomSheetBehavior.from(mBinding.layoutBehavior);
        mViewModel = new ViewModelProvider(this).get(MapFindingSourceModel.class);
        return mBinding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        if (searchEntity == null)
            searchEntity = new MapSourceSearchEntity();
        initMap();
        initPikers();
        initPopWindow();
        initEvent();
        initData();
        firstLocation();
    }

    /**
     * 首次进入设置装货地信息
     */
    private void firstLocation() {
        isFirst = true;
        if (loadAddress == null) {
            if (mViewModel.isLocServiceEnable(mContext)) {//开启定位
                checkLocationPermission();
            } else {//未开启定位
                searchEntity.setSearchLatitude(SharedPreferenceUtil.DEFAULT_LATITUDE);
                searchEntity.setSearchLongitude(SharedPreferenceUtil.DEFAULT_LONGITUDE);
                mViewModel.findSourceByMap(getActivity(), searchEntity);
            }
        } else {
            if (searchEntity.getSearchLatitude() > 0 && searchEntity.getSearchLatitude() > 0) {
                mViewModel.findSourceByMap(getActivity(), searchEntity);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (mapView != null)
            mapView.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        if (mapView != null) {
            mapView.onResume();
        }
    }

    /**
     * 检查是否有定位权限
     */
    private void checkLocationPermission() {
        EsayPermissions.with(getActivity())
                .permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        //有定位权限，中心点显示为当前定位
                        if (mLocationClient != null) {
                            mLocationClient.startLocation();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //没有定位权限，中心点显示为乌鲁木齐
                        searchEntity.setSearchLatitude(SharedPreferenceUtil.DEFAULT_LATITUDE);
                        searchEntity.setSearchLongitude(SharedPreferenceUtil.DEFAULT_LONGITUDE);
//                        searchEntity.setRadius("5000");
                        mViewModel.findSourceByMap(getActivity(), searchEntity);
                    }
                });
    }

    private void initPikers() {
        Date now = new Date();
        Calendar nowCal = Calendar.getInstance();
        nowCal.setTime(now);

        Calendar tomorrow = Calendar.getInstance();
        tomorrow.setTime(now);
        tomorrow.add(Calendar.DATE, 1);

        Calendar later = Calendar.getInstance();
        later.setTime(now);
        later.add(Calendar.DATE, 2);

        GoodsInfoTypeEntity3 t4 = new GoodsInfoTypeEntity3();
        t4.setName("不限");
        t4.setNo("0");
        timeBeans.add(t4);
        GoodsInfoTypeEntity3 t1 = new GoodsInfoTypeEntity3();
        t1.setName("今天");
        t1.setNo(DateUtils.timestampTo13(nowCal.getTime().getTime()) + "");
        timeBeans.add(t1);
        GoodsInfoTypeEntity3 t = new GoodsInfoTypeEntity3();
        t.setName("明天");
        t.setNo(DateUtils.timestampTo13(tomorrow.getTime().getTime()) + "");
        timeBeans.add(t);
        GoodsInfoTypeEntity3 t2 = new GoodsInfoTypeEntity3();
        t2.setName("明天以后");
        t2.setNo(DateUtils.timestampTo13(later.getTime().getTime()) + "");
        timeBeans.add(t2);
        timePicker = PickerHelper.with(mContext).getCommonPicker("装货时间", timeBeans, (options1, options2, options3, v) -> {
            timeChecked(options1);
        });

        weightBeans.add(new TypeChooseEntity("不限", 0, 0f));
        weightBeans.add(new TypeChooseEntity("0-10吨", 0, 10f));
        weightBeans.add(new TypeChooseEntity("10-30吨", 10, 30f));
        weightBeans.add(new TypeChooseEntity("30-50吨", 30, 50f));
        weightBeans.add(new TypeChooseEntity("50-100吨", 50, 100f));
        weightBeans.add(new TypeChooseEntity("100-500吨", 100, 500f));
        weightBeans.add(new TypeChooseEntity("500-1000吨", 500, 1000f));
        weightBeans.add(new TypeChooseEntity("1000吨以上", 1000, 99999f));

        weightPicker = PickerHelper.with(mContext).getCommonPicker(weightBeans, (options1, options2, options3, v) -> {
            inputGoodsWeight(options1);
        });
        weightPicker.setTitleText("货物重量");
    }

    private void initData() {
        inputRouterData();
        mViewModel.getGoodsType();
        mViewModel.getCarTypeAndCarLengthList("");
    }

    /**
     * 设置页面跳转携带数据
     */
    private void inputRouterData() {
        if (unloadingEntity != null) {
            AddressHelper.getInstance().findCode(unloadingEntity);
            loadingAddressInfo(1, unloadingEntity);
        }

        if (loadingEntity != null) {
            AddressHelper.getInstance().findCode(loadingEntity);
            loadingAddressInfo(0, loadingEntity);
        }

        if (goodsTypes != null) {
            inputGoodsType(goodsTypes);
        } else {
            goodsTypes = new ArrayList<>();
        }
        if (selectWeightPosition > 0) {
            inputGoodsWeight(selectWeightPosition);
        }

        if (selectRadiusPosition >= 0) {
            inputRadius(selectRadiusPosition);
        }

        if (goodsTypes.size() > 0 || selectWeightPosition > 0 || selectRadiusPosition >= 0) {
            closeFilterPlate(false);
            mBinding.arrowsIv.setImageResource(R.mipmap.icon_ex_lay_down);
            mBinding.pathTvBar.setVisibility(View.GONE);
            mBinding.windowLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化触摸、点击事件
     */
    private void initEvent() {
        mBinding.setOnClick(this::onClick);
        mBinding.carInfoLay.setOnTouchListener((v, event) -> {
            mBinding.carInfoLay.setVisibility(View.GONE);
            mViewModel.resetMarkersSmall();
            if (sheetBehavior != null && sheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
            MapSourceEntity entity = mViewModel.sources.get(mViewModel.lastPosition);
            if (mViewModel.markerLast != null) {
                mViewModel.markerLast.setIcon(BitmapDescriptorFactory.fromView(mViewModel.getMarkerView(entity, false)));
            }
            return true;
        });

        mViewModel.setUserInfo.observe(this, userData -> {
            if (isTakeOrders) {
//                if (currSourceInfo.getPattern().equals("0")) {//普通货源接单
                    LogisticsPermissionHelper.getInstance().checkPermissionToOrder(mContext,
                            currSourceInfo.getNo(), Integer.parseInt(currSourceInfo.getTerminal()), currSourceInfo.getMessagePrice());
//                } else {//竞价货源接单
//                    LogisticsPermissionHelper.getInstance().checkPermissionToQuoteOrder(mContext,
//                            currSourceInfo.getNo(), Integer.parseInt(currSourceInfo.getTerminal()), currSourceInfo.getMessagePrice()
//                    );
//                }
            } else {
//                if (currSourceInfo.getPattern().equals("0")) {//普通货源报价
                    LogisticsPermissionHelper.getInstance().checkPermissionToOrderQuote(mContext, currSourceInfo.getNo(),
                            Integer.parseInt(currSourceInfo.getTerminal()), currSourceInfo.getMessagePrice());
//                } else {//竞价货源报价
//                    LogisticsPermissionHelper.getInstance().checkPermissionToQuote(mContext,
//                            currSourceInfo.getNo(), Integer.parseInt(currSourceInfo.getTerminal()), currSourceInfo.getMessagePrice()
//                    );
//                }
            }
        });

        mViewModel.ldAddChangeListener.observe(this, aBoolean -> {
            if (aBoolean != null & aBoolean) {
                aMap.setOnCameraChangeListener(this);
            } else {
                aMap.setOnCameraChangeListener(null);
            }
        });

        mViewModel.ldIsClickMarker.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {
                mIsMarkerClick = true;
            } else {
                mIsMarkerClick = false;
            }
        });
        mViewModel.ldCurrSource.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer != null) {
//                    if (integer > 0 && mViewModel.getSources().size() >= integer) {
                    showSourceInfoWindow(mViewModel.getSources().get(integer));
//                    }
                }
            }
        });
        mViewModel.ldRefreshCar.observe(this, carInfo -> {
            if (checkCarInfo(carInfo)) {//发布承运
                gotoPublish();
            }
        });

        mViewModel.checkSourceLD.observe(this, checkStateEntity -> checkGoodsReceive(checkStateEntity));

        mViewModel.ldGoodsType.observe(this, entity3s -> {
            handleGoodsTypes(entity3s);
        });

        mViewModel.ldCarTypeMore.observe(this, list -> carTypePop.setCarTypeAndCarLength("", list));

        mViewModel.ldSearchResult.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                mBinding.mapView.setVisibility(View.VISIBLE);
                if (integer != null) {
                    MToast.showToast(getActivity(), String.format("当前城市共搜索到%d条信息", integer));
                    if (integer == 0) {
                        mBinding.carInfoLay.setVisibility(View.GONE);
                    }
                } else {
                    MToast.showToast(getActivity(), "搜索出错");
                }
            }
        });

        //底部弹窗视图Behavior
        sheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_COLLAPSED://折叠状态
                    case BottomSheetBehavior.STATE_HIDDEN://隐藏状态
//                    case BottomSheetBehavior.STATE_SETTLING://脱离手指自由滑动状态
                        mBinding.arrowsIv.setImageResource(R.mipmap.icon_ex_lay_up);
                        mBinding.pathTvBar.setVisibility(View.VISIBLE);
                        mBinding.windowLayout.setVisibility(View.GONE);
                        break;

                    case BottomSheetBehavior.STATE_DRAGGING://拖拽状态
                    case BottomSheetBehavior.STATE_EXPANDED://完全展开
                        mBinding.arrowsIv.setImageResource(R.mipmap.icon_ex_lay_down);
                        mBinding.pathTvBar.setVisibility(View.GONE);
                        mBinding.windowLayout.setVisibility(View.VISIBLE);
                        break;
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });

        mViewModel.ldUnfold.observe(this, data -> {
            if (data != null) {
                closeFilterPlate(data);
            }
        });
    }

    private void initPopWindow() {
        goodsTypePop = new ChooseTypePopWindow(mContext, "货物类型");
        goodsTypePop.setContainUnlimited(false);
        goodsTypePop.setOnResultClick((key1, key2, key3) -> {
            List<TypeChooseEntity> entity = (List<TypeChooseEntity>) key1;
            inputGoodsType(entity);
            carTypePop.resetAllFilterData();
            carTypeChooseResult(new GoodsSourceFilterEntity());
        });
        goodsTypePop.setOnDismissListener(() -> mBinding.popBg.setVisibility(View.GONE));


        carTypePop = new GoodsFilterPopWindow(mContext, false);
        carTypePop.setOnResultCallBack(result -> {
            carTypeChooseResult((GoodsSourceFilterEntity) result);
        });
        carTypePop.setOnDismissListener(() -> mBinding.popBg.setVisibility(View.GONE));
        radiusBeans.add(new TypeChooseEntity("0", "不限"));
        radiusBeans.add(new TypeChooseEntity("10", "10公里内"));
        radiusBeans.add(new TypeChooseEntity("50", "50公里内"));
        radiusBeans.add(new TypeChooseEntity("100", "100公里内"));
        radiusBeans.add(new TypeChooseEntity("200", "200公里内"));
        radiusBeans.add(new TypeChooseEntity("300", "300公里内"));
        radiusBeans.add(new TypeChooseEntity("500", "500公里内"));

        if (selectRadiusPosition >= 0 && selectRadiusPosition < radiusBeans.size()) {
            inputRadius(selectRadiusPosition);
        } else {
            searchEntity.setRadius(0);
        }

        radiusPicker = PickerHelper.with(getContext()).getCommonPicker(radiusBeans, (options1, options2, options3, v) -> {
            selectRadiusPosition = options1;
            inputRadius(options1);
        });
        radiusPicker.setSelectOptions(selectRadiusPosition);
        radiusPicker.setTitleText("半径");
    }

    /**
     * 录入半径
     */
    private void inputRadius(int options) {
        if (radiusBeans.size() >= options + 1) {
            TypeChooseEntity entity = radiusBeans.get(options);
            //重量
            String radiusStr = "";
            if (entity != null) {
                radiusStr = entity.getName();
                if (!TextUtils.isEmpty(entity.getNo())) {
                    searchEntity.setRadius(Integer.parseInt(entity.getNo()));
                } else {
                    searchEntity.setRadius(0);
                }
            }
            if (TextUtils.isEmpty(radiusStr)) {
                mBinding.radius.setText("距装货地半径");
                mBinding.radius.setTextColor(Color.parseColor("#C0C4CC"));
            } else {
                mBinding.radius.setText("装货地" + radiusStr.trim());
                mBinding.radius.setTextColor(Color.parseColor("#333333"));
            }
        }
    }

    /**
     * 校验车辆信息
     *
     * @param carInfos
     */
    private boolean checkCarInfo(List<CarInfo> carInfos) {
        if (carInfos == null) {
            MToast.showToast(getActivity(), "未获取到车辆信息");
            return false;
        } else if (carInfos.size() <= 0) {
            new RoundDialog.Builder(getActivity())
                    .title("无可用车辆")
                    .content("请先添加车辆")
                    .cancel("取消")
                    .confirm("去添加").confirmCallback(v1 -> {
                        AddCarActivity.start(mContext);
                    }
            ).show();
            return false;
        } else if (carInfos.size() == 1) {
            CarInfo carInfo = carInfos.get(0);
            if (carInfo.getIsComplete() == 0) {
                new RoundDialog.Builder(getActivity())
                        .title("车辆信息不完整")
                        .content("请先完善车型车长等信息")
                        .cancel("取消")
                        .confirm("去完善").confirmCallback(v1 -> {
                            if (!TextUtils.isEmpty(carInfo.getNo())) {
                                Intent intent = new Intent(getActivity(), AddCarInfoActivity.class);
                                intent.putExtra("carNo", Long.valueOf(carInfo.getNo()));
                                startActivity(intent);
                            } else {
                                MToast.showToast(getActivity(), "获取车辆信息失败");
                            }
                        }
                ).show();
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 身份和车辆信息都没问题就去发布承运
     */
    private void gotoPublish() {
        CargoMapEntity cargoMapEntity = new CargoMapEntity();
        if (loadAddress != null)
            cargoMapEntity.setSendLocation(loadAddress);
        if (unloadAddress != null)
            cargoMapEntity.setDestLocation(unloadAddress);
        ARouter.getInstance().build(PathLogistics.CarriagePushActivity)
                .withParcelable(RouterKey.DATA, cargoMapEntity)
                .navigation();
    }

    /**
     * 要求车型选择结果处理
     *
     * @param result
     */
    private void carTypeChooseResult(GoodsSourceFilterEntity result) {
        if (result == null)
            return;
        GoodsSourceFilterEntity filterEntity = result;
        String carTypeStr = "";
        //车型
        if (filterEntity.getCarType() != null && filterEntity.getCarType().size() > 0) {
            if (!TextUtils.isEmpty(filterEntity.getCarType().get(0).getNo()))
                searchEntity.setCarTypeNos(filterEntity.getCarType().get(0).getNo());
            if (!TextUtils.isEmpty(filterEntity.getCarType().get(0).getName()))
                carTypeStr += filterEntity.getCarType().get(0).getName() + "/";
        } else {
            searchEntity.setCarTypeNos("");
        }

        //车长
        if (filterEntity.getLengthType() != null && filterEntity.getLengthType().size() > 0) {
            if (!TextUtils.isEmpty(filterEntity.getLengthType().get(0).getNo()))
                searchEntity.setCarLenNos(filterEntity.getLengthType().get(0).getNo());
            if (!TextUtils.isEmpty(filterEntity.getLengthType().get(0).getName()))
                carTypeStr += filterEntity.getLengthType().get(0).getName() + "/";
        } else {
            searchEntity.setCarLenNos("");
        }

        if (!TextUtils.isEmpty(carTypeStr)) {
            carTypeStr = carTypeStr.substring(0, carTypeStr.length() - 1);
            mBinding.carType.setText(carTypeStr);
            mBinding.carType.setTextColor(Color.parseColor("#333333"));
        } else {
            mBinding.carType.setText("请选择要求车型等");
            mBinding.carType.setTextColor(Color.parseColor("#C0C4CC"));
        }
    }

    /**
     * 展示货源信息
     *
     * @param sourceEntity
     */
    private void showSourceInfoWindow(MapSourceEntity sourceEntity) {
        if (sourceEntity == null)
            return;
        currSourceInfo = sourceEntity;

        if (mViewModel.isLocServiceEnable(mContext) && !TextUtils.isEmpty(sourceEntity.getDistance())) {
            mBinding.distanceTv.setText(Double.parseDouble(sourceEntity.getDistance()) < 1000 ? "距您 1km以内" :
                    String.format("距您%skm", NumberUtil.trim0(Double.parseDouble(sourceEntity.getDistance()) / 1000)));
            mBinding.distanceTv.setVisibility(View.VISIBLE);
        } else {//没开启定位或者后台未返值，则不展示距离信息
            mBinding.distanceTv.setVisibility(View.GONE);
        }

//        if (sourceEntity.getPattern().equals("1")) {
//            mBinding.carRequireInfo.setVisibility(View.GONE);
//            mBinding.carTypeIv.setVisibility(View.GONE);
//            mBinding.biddingMarker.setVisibility(View.VISIBLE);
//            mBinding.carTypeIv.setVisibility(View.GONE);
//            //报价资格信息
//            mBinding.qualificationInfo.setVisibility(View.VISIBLE);
//            mBinding.qualificationInfo.setText("报价资格：" + sourceEntity.getOfferType());
//            //总运费
//            if (!TextUtils.isEmpty(currSourceInfo.getAllFreight())) {
//                mBinding.totalFreight.setText(NumberUtil.trim0(currSourceInfo.getAllFreight()) + "元");
//            }
//            mBinding.priceHint.setText("运费单价：");
//            if (!TextUtils.isEmpty(sourceEntity.getFreight())) {
//                mBinding.priceTop.setText(NumberUtil.trim0(currSourceInfo.getFreight()) + sourceEntity.getFreightUnit());
//            }
//        } else {
        if (sourceEntity.getPattern().equals("1")) {//竞价
            mBinding.biddingMarker.setVisibility(View.VISIBLE);
        } else {//普通
            mBinding.biddingMarker.setVisibility(View.GONE);
        }
        mBinding.qualificationInfo.setVisibility(View.GONE);
//        mBinding.carTypeIv.setVisibility(View.VISIBLE);
//        if (!TextUtils.isEmpty(sourceEntity.getTransportType()) && sourceEntity.getTransportType().equals("0")) {//零担
//            mBinding.carTypeIv.setImageResource(R.drawable.icon_less_than_tag);
//        } else {//默认整车
//            mBinding.carTypeIv.setImageResource(R.drawable.icon_carload_tag);
//        }
        //车辆要求信息
        String requireStr = "";
        if (!TextUtils.isEmpty(currSourceInfo.getCarTypeName())) {
            requireStr += currSourceInfo.getCarTypeName() + " ";
        }
        if (!TextUtils.isEmpty(currSourceInfo.getCarLenName())) {
            requireStr += currSourceInfo.getCarLenName() + " ";
        }
        if (!TextUtils.isEmpty(currSourceInfo.getHeightHurdle())) {
            requireStr += "栏高" + currSourceInfo.getHeightHurdle() + "米 ";
        }
        requireStr += sourceEntity.getIsDump();
        if (!TextUtils.isEmpty(requireStr)) {
            mBinding.carRequireInfo.setText(requireStr);
            mBinding.carRequireInfo.setVisibility(View.VISIBLE);
        } else {
            mBinding.carRequireInfo.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(currSourceInfo.getFreightType()) && currSourceInfo.getFreightType().equals("1")) {
            mBinding.totalFreight.setText("电议");
        } else if (!TextUtils.isEmpty(currSourceInfo.getAllFreight())) {
            mBinding.totalFreight.setText(NumberUtil.trim0(currSourceInfo.getAllFreight()) + "元");
        }
        mBinding.priceHint.setText("信息费：");
        if (!TextUtils.isEmpty(sourceEntity.getMessagePrice())) {
            mBinding.priceTop.setText(NumberUtil.trim0(currSourceInfo.getMessagePrice()) + "元");
        }
//        }

        //货源的类型和重量信息
        String sourceInfo = "";
        if (!TextUtils.isEmpty(currSourceInfo.getGoodsLastTypeName())) {
            sourceInfo += currSourceInfo.getGoodsLastTypeName() + " ";
        }
        if (!TextUtils.isEmpty(currSourceInfo.getWeight())) {
            sourceInfo += currSourceInfo.getWeight();
        }
        if (!TextUtils.isEmpty(sourceInfo)) {
            mBinding.sourceInfo.setText(sourceInfo);
            mBinding.sourceInfo.setVisibility(View.VISIBLE);
        } else {
            mBinding.sourceInfo.setVisibility(View.GONE);
        }

        //收发地信息
        String addressInfo = "";
        if (!TextUtils.isEmpty(currSourceInfo.getCityName())) {
            addressInfo += currSourceInfo.getCityName() + " ";
        }
        if (!TextUtils.isEmpty(currSourceInfo.getDistrictName())) {
            addressInfo += currSourceInfo.getDistrictName() + " ";
        }
        addressInfo += "→";

        if (!TextUtils.isEmpty(currSourceInfo.getDestCityName())) {
            addressInfo += " " + currSourceInfo.getDestCityName();
        }
        if (!TextUtils.isEmpty(currSourceInfo.getDestDistrictName())) {
            addressInfo += " " + currSourceInfo.getDestDistrictName();
        }
        mBinding.addressInfo.setText(addressInfo);

        String loadTime = CargoConstant.stampFormatListLoadTime(
                currSourceInfo.getShipmentTime(), currSourceInfo.getStartPointTime(),
                currSourceInfo.getShipmentEndTime(), currSourceInfo.getEndPointTime());
        mBinding.loadingInfo.setText(loadTime + " 装货");

        mBinding.carInfoLay.setVisibility(View.VISIBLE);
    }

    /**
     * 选中时间界面显示
     *
     * @param options1
     */
    private void timeChecked(int options1) {
        if (timeBeans.size() >= options1 + 1) {
            GoodsInfoTypeEntity3 entity = timeBeans.get(options1);
            timeStr = entity.getName();
            if (!TextUtils.isEmpty(timeStr)) {
                if (timeStr.equals("不限")) {
                    mBinding.loadTime.setText("请选择装货时间");
                    mBinding.loadTime.setTextColor(Color.parseColor("#C0C4CC"));
                } else {
                    mBinding.loadTime.setText(timeStr);
                    mBinding.loadTime.setTextColor(Color.parseColor("#333333"));
                }

                if (timeStr.equals("明天以后")) {
                    searchEntity.setShipmentTime(entity.getNo());
                    searchEntity.setShipmentEndTime("");
                } else {
                    searchEntity.setShipmentTime("");
                    searchEntity.setShipmentEndTime(entity.getNo());
                }
            }
        }
    }

    /**
     * 录入货物类型
     *
     * @param entity
     */
    private void inputGoodsType(List<TypeChooseEntity> entity) {
        goodsTypeNos = "";
        goodsTypeEntities.clear();
        if (entity == null || entity.size() == 0 || (entity.size() > 0 && entity.get(0).getName().equals("不限"))) {
            mBinding.goodsType.setText("请选择货物类型");
            mBinding.goodsType.setTextColor(Color.parseColor("#C0C4CC"));
            searchEntity.setGoodsModeNos("");
            mViewModel.getCarTypeAndCarLengthList(goodsTypeNos);
            return;
        }
        goodsTypeEntities.addAll(entity);
        String goodsTypeStr = "";

        if (entity.size() > 0) {
            for (TypeChooseEntity typeEntity : goodsTypeEntities) {
                if (!TextUtils.isEmpty(typeEntity.getName())) {
                    goodsTypeStr = goodsTypeStr + typeEntity.getName() + "/";
                }
                if (!TextUtils.isEmpty(typeEntity.getNo())) {
                    goodsTypeNos += typeEntity.getNo() + ",";
                }
            }
            if (goodsTypeNos.length() > 0) {
                goodsTypeNos = goodsTypeNos.substring(0, goodsTypeNos.length() - 1);
            }

            if (goodsTypeStr.length() > 0) {
                goodsTypeStr = goodsTypeStr.substring(0, goodsTypeStr.length() - 1);
            }
        }

        if (TextUtils.isEmpty(goodsTypeStr)) {
            mBinding.goodsType.setText("请选择货物类型");
            mBinding.goodsType.setTextColor(Color.parseColor("#C0C4CC"));
        } else {
            mBinding.goodsType.setText(goodsTypeStr.trim());
            mBinding.goodsType.setTextColor(Color.parseColor("#333333"));
        }
        searchEntity.setGoodsModeNos(goodsTypeNos);
        mViewModel.getCarTypeAndCarLengthList(goodsTypeNos);
    }

    /**
     * 录入货物重量
     */
    private void inputGoodsWeight(int options) {
        if (weightBeans.size() >= options + 1) {
            if (options == 0) {
                mBinding.weight.setText("请选择货物运输量");
                mBinding.weight.setTextColor(Color.parseColor("#C0C4CC"));
                searchEntity.setMinWeight("");
                searchEntity.setMaxWeight("");
                return;
            }
            TypeChooseEntity entity = weightBeans.get(options);
            //重量
            String weightStr = "";
            if (entity.getMinValue() >= 0) {
                searchEntity.setMinWeight(entity.getMinValue() + "");
                weightStr += NumberUtil.trim0(entity.getMinValue());
            } else {
                searchEntity.setMinWeight("");
            }

            if (entity.getMaxValue() > 0) {
                searchEntity.setMaxWeight(entity.getMaxValue() + "");
                if (entity.getMinValue() == 1000) {
                    weightStr += "吨以上";
                } else
                    weightStr += "-" + NumberUtil.trim0(entity.getMaxValue()) + "吨";
            } else {
                searchEntity.setMaxWeight("");
                weightStr += "吨以上";
            }

            if (TextUtils.isEmpty(weightStr)) {
                mBinding.weight.setText("请选择货物运输量");
                mBinding.weight.setTextColor(Color.parseColor("#C0C4CC"));
            } else {
                mBinding.weight.setText(weightStr.trim());
                mBinding.weight.setTextColor(Color.parseColor("#333333"));
            }
        }
    }

    /**
     * 处理货物类型数据
     *
     * @param entities
     */
    private void handleGoodsTypes(List<GoodsInfoTypeEntity3> entities) {
        List<TypeChooseEntity> chooseEntities = new ArrayList<>();
        if (entities != null && entities.size() > 0) {
            for (GoodsInfoTypeEntity3 entity : entities) {
                TypeChooseEntity entity1 = new TypeChooseEntity();
                entity1.setSelect(false);
                entity1.setName(entity.getName());
                entity1.setNo(entity.getNo());
                if (goodsTypeEntities.size() > 0) {
                    for (TypeChooseEntity en : goodsTypeEntities) {
                        if (entity.getNo().equals(en.getNo())) {
                            entity1.setSelect(true);
                        }
                    }
                }
                chooseEntities.add(entity1);
            }
        }
        goodsTypePop.setData(chooseEntities);
    }

    /**
     * 初始化地图（高德3D地图）
     */
    private void initMap() {
        mapView = mBinding.mapView;
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        mViewModel.setAMap(aMap);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(mViewModel.zoomLevel));//缩放比例
        /**
         * 设置一些aMap的属性
         */
//        aMap.setMapTextZIndex(2);//地图文字的Z轴指数,设置为2可以将地图底图文字设置在添加的覆盖物之上
        UiSettings uiSettings = aMap.getUiSettings();//地图的UI设置控制器
        uiSettings.setZoomControlsEnabled(false);//是显示缩放按钮
        uiSettings.setCompassEnabled(false);// 设置指南针是否显示
        uiSettings.setScaleControlsEnabled(false);// 设置比例尺是否显示
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        uiSettings.setRotateGesturesEnabled(true);// 设置地图旋转是否可用
        uiSettings.setTiltGesturesEnabled(true);// 设置地图倾斜是否可用
        aMap.setOnCameraChangeListener(this);        //地图点击监听
        aMap.setOnMapTouchListener(motionEvent -> {
            if (sheetBehavior != null && sheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
        initLocation();
    }

    /**
     * 初始化定位服务信息
     */
    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
    }

    public void loadingAddressInfo(AMapAddressEntity entity) {
        if (entity == null)
            return;
        loadingAddressInfo(entity.getType(), entity);
    }

    /**
     * 设置地址信息
     *
     * @param type   地址类型（起点、终点）
     * @param entity 地址信息数据
     */
    public void loadingAddressInfo(int type, AMapAddressEntity entity) {
        AddressHelper.getInstance().findCode(entity);
        CargoPublishEntity.LocationEntity locationEntity = new CargoPublishEntity.LocationEntity();
        locationEntity.setProvince(entity.getProvince());
        locationEntity.setProvinceNo(entity.getProvinceNo());
        locationEntity.setCity(entity.getCity());
        locationEntity.setCityNo(entity.getCityNo());
        locationEntity.setDistrict(entity.getDistrict());
        locationEntity.setDistrictNo(entity.getDistrictNo());
        locationEntity.setLatitude(entity.getLatitude());
        locationEntity.setLongitude(entity.getLongitude());
        locationEntity.setAddress(entity.getSnippet());
        if (type == 0) {
            loadAddress = locationEntity;
            if (!TextUtils.isEmpty(entity.getCity()))
                searchCity = entity.getCity().replace("市", "");
            if (!TextUtils.isEmpty(loadAddress.getAddress())) {
                mBinding.loadPlaceEdit.setText(loadAddress.getAddress());
            }
            if (loadAddress.getLatitude() > 0 && loadAddress.getLongitude() > 0) {
                searchEntity.setSearchLatitude(loadAddress.getLatitude());
                searchEntity.setSearchLongitude(loadAddress.getLongitude());
            }
            mBinding.carInfoLay.setVisibility(View.GONE);
        } else if (type == 1) {
            unloadAddress = locationEntity;
            if (!TextUtils.isEmpty(unloadAddress.getAddress())) {
                mBinding.unloadPlaceEdit.setText(unloadAddress.getAddress());
                mBinding.endClean.setVisibility(View.VISIBLE);
            }
            searchEntity.setDestProvinceNo(unloadAddress.getProvinceNo());
            searchEntity.setDestCityNo(unloadAddress.getCityNo());
        }

        if (loadAddress != null && unloadAddress != null) {
            OperateGoodsSourcePlaceVO placeVO = new OperateGoodsSourcePlaceVO();
            placeVO.setLatitude(loadAddress.getLatitude());
            placeVO.setLongitude(loadAddress.getLongitude());
            placeVO.setDestLatitude(unloadAddress.getLatitude());
            placeVO.setDestLongitude(unloadAddress.getLongitude());
            mViewModel.setPlanRouteInfo(placeVO);
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (isFirst) {
            isFirst = false;
            return;
        }
        if (!isPeopleMade) {
            if (!mIsMarkerClick) {
                if (mViewModel.zoomLevel != cameraPosition.zoom) {
                    //地图缩放，不做数据搜索操作
                    mViewModel.zoomLevel = cameraPosition.zoom;
                } else {
                    //地图移动不需要操作搜索结果
                    locationLatLng = cameraPosition.target;
//                    searchEntity.setSearchLatitude(locationLatLng.latitude);
//                    searchEntity.setSearchLongitude(locationLatLng.longitude);
//                    mViewModel.findSourceByMap(getActivity(), searchEntity);
                }
            } else {
                mIsMarkerClick = false;
            }
        } else {
            isPeopleMade = false;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.pop_bg:
                mBinding.popBg.setVisibility(View.GONE);
                break;

            case R.id.end_clean:
                setDestinationAddressEmpty();
                if (aMap != null) {
                    aMap.clear();
                    if (mViewModel.sources != null && mViewModel.sources.size() > 0 && mViewModel.markerEntityList != null && mViewModel.markerEntityList.size() > 0) {
                        mViewModel.markerEntityList.clear();
                        for (int i = 0; i < mViewModel.sources.size(); i++) {
                            MapSourceEntity infoEntity = mViewModel.sources.get(i);
                            if (infoEntity.getLatitude() > 0 && infoEntity.getLongitude() > 0) {
                                LatLng latLng = new LatLng(infoEntity.getLatitude(), infoEntity.getLongitude());
                                MarkerEntity markerEntity;
                                markerEntity = new MarkerEntity(latLng, mViewModel.getMarkerView(infoEntity, false), null);
                                mViewModel.markerEntityList.add(markerEntity);
                            }
                        }
                        mViewModel.addMarkers(mViewModel.sources);
                    }
                    if (mViewModel.place != null) {
                        mViewModel.place.setDestLatitude(0);
                        mViewModel.place.setDestLongitude(0);
                    }
                }
                break;

            case R.id.window_layout:
                break;
            case R.id.car_info_inner_lay:
                if (currSourceInfo != null) {
                    if (currSourceInfo.getPattern().equals("1")) {
                        FreightPrjDetailActivity.start(getContext(), currSourceInfo.getNo(), false, false);//竞价货源
                    } else {
                        GeneralPrjDetailActivity.start(getContext(), currSourceInfo.getNo(), 0, false);
                    }
                }
                break;


            case R.id.choose_goods_type:
                goodsTypePop.showDownPopwindow(mBinding.chooseGoodsType, true);
                goodsTypePop.setTittle("货物类型");
                goodsTypePop.setLeftBtnStr("重置");
                mBinding.popBg.setVisibility(View.VISIBLE);
                break;

            case R.id.choose_radius:
                if (radiusPicker != null) {
                    radiusPicker.show();
                }
                break;

            case R.id.choose_car_type:
                carTypePop.showDownPopwindow(mBinding.chooseCarType, true);
                mBinding.popBg.setVisibility(View.VISIBLE);
                break;

            case R.id.choose_weight:
                if (weightPicker != null) {
                    weightPicker.show();
                }

                break;

            case R.id.choose_time:
                if (timePicker != null) {
                    timePicker.show();
                }
                break;

            case R.id.search_source:
                if (loadAddress != null && loadAddress.getLongitude() > 0 && loadAddress.getLatitude() > 0) {
                    mBinding.carInfoLay.setVisibility(View.GONE);
                    isPeopleMade = true;
                    searchEntity.setSearchLatitude(loadAddress.getLatitude());
                    searchEntity.setSearchLongitude(loadAddress.getLongitude());
//                    searchEntity.setRadius("5000");
                    mViewModel.findSourceByMap(getActivity(), searchEntity);
                }
                break;

            case R.id.arrows_iv_bar:
            case R.id.path_tv_bar:
                if (sheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                break;
        }
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
//            case R.id.published_carrier:
//                identityCheck();
//                break;

            case R.id.letter_lay://函询
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if (currSourceInfo.getPattern().equals("1")) {
                    InquireByLetterActvity.start(mContext, 1, currSourceInfo.getUsername(), currSourceInfo.getUserNo(), currSourceInfo.getNo(), currSourceInfo.getCityName() + "\u3000" + currSourceInfo.getDistrictName() + "->" + currSourceInfo.getDestCityName() + "\u3000" + currSourceInfo.getDestCityName());
                } else {
                    InquireByLetterActvity.start(mContext, 0, currSourceInfo.getUsername(), currSourceInfo.getUserNo(), currSourceInfo.getNo(), currSourceInfo.getCityName() + "\u3000" + currSourceInfo.getDistrictName() + "->" + currSourceInfo.getDestCityName() + "\u3000" + currSourceInfo.getDestCityName());
                }
                break;

            case R.id.invite_lay://邀请
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if (currSourceInfo != null && !TextUtils.isEmpty(currSourceInfo.getTerminal())) {
                    switch (currSourceInfo.getTerminal()) {
                        case "1":
                            if (!TextUtils.isEmpty(currSourceInfo.getCompanyNo())) {
                                LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, currSourceInfo.getCompanyNo(), 1);
                            }
                            break;

                        case "2":
                            if (!TextUtils.isEmpty(currSourceInfo.getTeamNo())) {
                                LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, currSourceInfo.getTeamNo(), 2);
                            }
                            break;

                        case "3":
                            if (!TextUtils.isEmpty(currSourceInfo.getUserNo())) {
                                LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, currSourceInfo.getUserNo(), 0);
                            }
                            break;
                    }
                }
                break;

            case R.id.order_receive://接单
                isTakeOrders = true;
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if (currSourceInfo != null && !TextUtils.isEmpty(currSourceInfo.getNo())) {
                    mViewModel.goodsSourceStatusCheck(currSourceInfo.getNo());
                }
                break;

            case R.id.order_offer://报价
                isTakeOrders = false;
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if (currSourceInfo != null && !TextUtils.isEmpty(currSourceInfo.getNo())) {
                    mViewModel.goodsSourceStatusCheck(currSourceInfo.getNo());
                }
                break;

            case R.id.im_lay:
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if (currSourceInfo != null) {
                    // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                    if (!TextUtils.isEmpty(currSourceInfo.getContrctsImAccount())) {
                        IMUtils.getInstance().buildSingleTalking(currSourceInfo.getContrctsImAccount());
                    } else {
                        if (!TextUtils.isEmpty(currSourceInfo.getImAccount())) {
                            IMUtils.getInstance().buildSingleTalking(currSourceInfo.getImAccount());
                        }
                    }
                }
                break;

            case R.id.newest_source_lay:
                if (newestEntity != null && !TextUtils.isEmpty(newestEntity.getNo())) {
                    CarriageDetailActivity.start(mContext, newestEntity.getNo(), 2);
                }
                break;

            case R.id.call_lay:
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if (currSourceInfo != null && !TextUtils.isEmpty(currSourceInfo.getConnectionPhone())) {
                    new RoundDialog.Builder(mContext)
                            .title("确认呼叫")
                            .content(currSourceInfo.getConnectionPhone())
                            .confirm("确定")
                            .cancel("取消")
                            .cancelable(false)
                            .confirmCallback(on -> {
                                LogisticsLogUtils.getInstance().logisticsFlow("6", "货源联系人", "icon");
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + currSourceInfo.getConnectionPhone());
                                intent.setData(data);
                                startActivity(intent);
                            }).show();
                }
                break;

            case R.id.address_info:
                if (currSourceInfo != null && !TextUtils.isEmpty(currSourceInfo.getNo())) {
                    //判断货源是否是已接单或不存在
                    if (!currSourceInfo.getStatus().equals("1")) {
                        showTipDialog("该货源已不存在，请选择其他货源接单。");
                    } else if (!currSourceInfo.getState().equals("0")) {
                        showTipDialog("该货源已被接单，请选择其他货源接单。");
                    } else {
                        if (currSourceInfo.getPattern().equals("1")) {
                            FreightPrjDetailActivity.start(mContext, currSourceInfo.getNo(), false, false);//竞价货源
                        } else {
                            GeneralPrjDetailActivity.start(mContext, currSourceInfo.getNo(), 0, false);//普通货源
                        }
                    }
                }
                break;

            case R.id.load_place_edit://装货地
                String loadStr1 = "";
                if (loadingEntity != null) {
                    loadStr1 = loadingEntity.getSnippet();
                }
                if (!TextUtils.isEmpty(loadStr1))
                    ((FindByMapActivity) getActivity()).selectAddress(loadStr1, 0);
                break;

            case R.id.unload_place_edit://卸货地
                String loadStr2 = "";
                String unloadStr = "";
                if (loadingEntity != null) {
                    loadStr2 = loadingEntity.getSnippet();
                }
                if (unloadingEntity != null) {
                    unloadStr = unloadingEntity.getSnippet();
                }
                if (!TextUtils.isEmpty(loadStr2))
                    ((FindByMapActivity) getActivity()).selectAddress(TextUtils.isEmpty(unloadStr) ? TextUtils.isEmpty(loadStr2) ? "" : loadStr2 : unloadStr, 1);
                break;
        }
    }

    /**
     * 筛选版的打开与关闭
     *
     * @param isClose 是否关闭筛选面板
     */
    private void closeFilterPlate(boolean isClose) {
        if (!isClose && sheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
            sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        } else if (sheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    }

    /**
     * 车主身份校验
     */
    private void identityCheck() {
        //未登录前往登录页面
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (!UserOperating.getInstance().isAuthRealName()) {
            //检验是否实名认证
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("当前功能需要实名认证才能操作，是否去认证？")
                    .cancel("取消")
                    .confirm("确定").confirmCallback(v1 -> {
                        CertificationActivity.start(mContext);
                    }
            ).show();
            return;
        }
        //先判断是否认证了司机
        if (!UserOperating.getInstance().isAuthDriver()) {
            new RoundDialog.Builder(getActivity())
                    .title("未认证司机")
                    .content("请先去进行司机认证才能操作")
                    .cancel("取消")
                    .confirm("确定").confirmCallback(v1 -> {
                        startActivity(new Intent(getActivity(), AddDriverInfoActivity.class));
                    }
            ).show();
            return;
        }
        //在判断是否有可用车辆
        if (!UserOperating.getInstance().getUserInfo().isHasCar()) {
            new RoundDialog.Builder(getActivity())
                    .title("无可用车辆")
                    .content("请先添加车辆")
                    .cancel("取消")
                    .confirm("去添加").confirmCallback(v1 -> {
                        AddCarActivity.start(mContext);
                    }

            ).show();
            return;
        }
        mViewModel.getCarInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void acceptEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CARRIAGE_RELEASE_SUCCESS_MAP_DATA) {
            if (event.getMessageData() != null) {
                CargoMapEntity mapEntity = (CargoMapEntity) event.getMessageData();
                inputSourceInfo(mapEntity);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            if (searchEntity != null)
                mViewModel.findSourceByMap(getActivity(), searchEntity);
        }
    }

    /**
     * 输入货源信息
     *
     * @param mapEntity
     */
    private void inputSourceInfo(CargoMapEntity mapEntity) {
        if (mapEntity == null)
            return;

        //清空之前的搜索条件
        searchEntity.setNull();
        mBinding.goodsType.setText("请选择货物类型");
        mBinding.goodsType.setTextColor(Color.parseColor("#C0C4CC"));
        mBinding.loadTime.setText("请选择装货时间");
        mBinding.loadTime.setTextColor(Color.parseColor("#C0C4CC"));
        mBinding.carType.setText("请选择要求车型等");
        mBinding.carType.setTextColor(Color.parseColor("#C0C4CC"));

        newestEntity = mapEntity;
        StringBuilder addressInfo = new StringBuilder();
        if (mapEntity.getSendLocation() != null) {
            loadAddress = mapEntity.getSendLocation();
            if (!TextUtils.isEmpty(loadAddress.getCity())) {
                addressInfo.append(loadAddress.getCity().replace("市", ""));
            }
            if (!TextUtils.isEmpty(loadAddress.getDistrict())) {
                addressInfo.append(loadAddress.getDistrict().replace("区", ""));
            }

            if (!TextUtils.isEmpty(loadAddress.getAddress())) {
                mBinding.loadPlaceEdit.setText(loadAddress.getAddress());
            } else {
                mBinding.loadPlaceEdit.setText("");
            }

            if (loadAddress.getLatitude() > 0 && loadAddress.getLongitude() > 0) {
                searchEntity.setSearchLatitude(loadAddress.getLatitude());
                searchEntity.setSearchLongitude(loadAddress.getLongitude());
//                searchEntity.setRadius("5000");
                mViewModel.findSourceByMap(getActivity(), searchEntity);
                if (!TextUtils.isEmpty(loadAddress.getCity()))
                    searchCity = loadAddress.getCity().replace("市", "");
            }
        } else {
            loadAddress = null;
        }

        addressInfo.append(" → ");

        if (mapEntity.getDestLocation() != null) {
            unloadAddress = mapEntity.getDestLocation();
            searchEntity.setDestProvinceNo(unloadAddress.getProvinceNo());
            searchEntity.setDestCityNo(unloadAddress.getCityNo());
            if (!TextUtils.isEmpty(unloadAddress.getCity())) {
                addressInfo.append(unloadAddress.getCity().replace("市", ""));
            }
            if (!TextUtils.isEmpty(unloadAddress.getDistrict())) {
                addressInfo.append(unloadAddress.getDistrict().replace("区", ""));
            }
            if (!TextUtils.isEmpty(unloadAddress.getAddress())) {
                mBinding.unloadPlaceEdit.setText(unloadAddress.getAddress());
                mBinding.endClean.setVisibility(View.VISIBLE);
            } else {
                mBinding.unloadPlaceEdit.setText("");
                mBinding.endClean.setVisibility(View.GONE);
            }
        } else {
            unloadAddress = null;
            setDestinationAddressEmpty();
        }

        mBinding.newestSourceInfo.setText(addressInfo.toString().trim());
        mBinding.newestSourceLay.setVisibility(View.VISIBLE);
    }

    /**
     * 设置卸货地信息为空
     */
    private void setDestinationAddressEmpty() {
        mBinding.endClean.setVisibility(View.GONE);
        mBinding.unloadPlaceEdit.setText("");
        searchEntity.setDestProvinceNo("");
        searchEntity.setDestCityNo("");
    }

    private void showTipDialog(String content) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content(DefaultUtil.getString(content))
                .confirm("我知道了")
                .singleBtn(true)
                .cancelable(false)
                .show();
    }

    /**
     * 检验货源状态是否可接单或报价
     *
     * @param stateEntity
     */
    public void checkGoodsReceive(CheckStateEntity stateEntity) {
        if (stateEntity.goodsIsGone()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源不存在，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .show();
        } else if (stateEntity.goodsIsReceipted()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源已被接单，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .show();

        } else {
            if (currSourceInfo.getNo().equals(stateEntity.getNo())) {
                mViewModel.getLogisticsPermissions(mContext);
            }
        }
    }
}
